package server

import (
	"0519/common/initialize"
	"0519/common/pkg"
	course "0519/common/proto"
	"0519/rpc/models"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/robfig/cron"
	"strconv"
	"time"
)

func UserLogin(in *course.UserLoginReq) (*course.UserLoginResp, error) {
	u := models.User{}
	mobile, err := u.GetUserMobile(in.Mobile)
	if err != nil {
		return nil, errors.New("用户还未注册")
	}
	if mobile.ID == 0 {
		return nil, errors.New("用户还未注册")
	}
	if mobile.Password != in.Password {
		return nil, errors.New("用户密码错误")
	}
	return &course.UserLoginResp{
		UserId: int64(mobile.ID),
	}, nil
}

func CourseAdd(in *course.CourseAddReq) (*course.CourseAddResp, error) {
	u := models.User{}
	c := models.Course{}
	user, err := u.GetUserId(in.UserId)
	if err != nil {
		return nil, errors.New("用户查询失败")
	}
	if user.ID != 1 {
		return nil, errors.New("该用户不是管理员,无法发布课程")
	}
	add, err := c.CourseAdd(in)
	if err != nil {
		return nil, errors.New("发布课程失败")
	}
	return &course.CourseAddResp{
		CourseId: int64(add.ID),
	}, nil
}

func CourseList(in *course.CourseListReq) (*course.CourseListResp, error) {
	u := models.User{}
	c := models.Course{}
	user, err := u.GetUserId(in.UserId)
	if err != nil {
		return nil, errors.New("用户查询失败")
	}
	if user.ID != 1 {
		return nil, errors.New("该用户不是管理员,无法列表展示")
	}
	getCourse, err := c.GetCourse()
	if err != nil {
		return nil, errors.New("列表展示失败")
	}
	var list []*course.CourseList
	for _, i := range getCourse {
		list = append(list, &course.CourseList{
			CourseId: int64(i.ID),
			Name:     i.Name,
			Price:    float32(i.Price),
			Stock:    int64(i.Stock),
			State:    int64(i.State),
		})
	}

	marshal, err := json.Marshal(list)
	if err != nil {
		return nil, err
	}
	initialize.Rdb.HMSet(context.Background(), "CreateOrder", 123)
	initialize.Rdb.Set(context.Background(), "CreateOrder", marshal, time.Minute*50)

	return &course.CourseListResp{List: list}, nil
}

func CourseInfo(in *course.CourseInfoReq) (*course.CourseInfoResp, error) {
	u := models.User{}
	c := models.Course{}
	user, err := u.GetUserId(in.UserId)
	if err != nil {
		return nil, errors.New("用户查询失败")
	}
	if user.ID != 1 {
		return nil, errors.New("该用户不是管理员,无法详情展示")
	}
	cour, err := c.GetCourseId(in.CourseId)
	if err != nil {
		return nil, errors.New("详情展示失败")
	}
	var list []*course.CourseInfo
	for _, i := range cour {
		list = append(list, &course.CourseInfo{
			CourseId:          int64(i.ID),
			Name:              i.Name,
			CourseInformation: i.CourseInformation,
			CourseDuration:    i.CourseDuration,
			Price:             float32(i.Price),
			Stock:             int64(i.Stock),
			State:             int64(i.State),
			Picture:           i.Picture,
		})
	}

	return &course.CourseInfoResp{List: list}, nil

}
func CourseUpdateState(in *course.CourseUpdateStateReq) (*course.CourseUpdateStateResp, error) {
	u := models.User{}
	c := models.Course{}
	user, err := u.GetUserId(in.UserId)
	if err != nil {
		return nil, errors.New("用户查询失败")
	}
	if user.ID != 1 {
		return nil, errors.New("该用户不是管理员,无法修改状态")
	}
	err = c.CourseUpdateState(in)
	if err != nil {
		return nil, errors.New("状态修改失败")
	}
	return &course.CourseUpdateStateResp{Success: true}, nil

}
func CourseDeleted(in *course.CourseDeletedReq) (*course.CourseDeletedResp, error) {
	u := models.User{}
	c := models.Course{}
	user, err := u.GetUserId(in.UserId)
	if err != nil {
		return nil, errors.New("用户查询失败")
	}
	if user.ID != 1 {
		return nil, errors.New("该用户不是管理员,无法删除")
	}
	err = c.CourseDeleted(in.CourseId)
	if err != nil {
		return nil, errors.New("删除失败")
	}
	return &course.CourseDeletedResp{Success: true}, nil
}
func CreateDiscountCourse(in *course.CreateDiscountCourseReq) (*course.CreateDiscountCourseResp, error) {
	u := models.User{}
	c := models.Course{}
	d := models.DiscountCourse{}
	user, err := u.GetUserId(in.UserId)
	if err != nil {
		return nil, errors.New("用户查询失败")
	}
	if user.ID != 1 {
		return nil, errors.New("该用户不是管理员,无法限时优惠发布商品")
	}
	id, err := c.GetCourseIds(in.CourseId)
	if err != nil {
		return nil, errors.New("查询课程失败")
	}
	num := id.Stock - int(in.Num)
	if num < 0 {
		return nil, errors.New("库存不足")
	}
	discountCourse, err := d.CreateDiscountCourse(in, id.Price, num)
	if err != nil {
		return nil, errors.New("限时优惠课程发布失败")
	}

	return &course.CreateDiscountCourseResp{DiscountCourseId: int64(discountCourse.ID)}, nil
}
func CreateDiscountCourseOrder(in *course.CreateDiscountCourseOrderReq) (*course.CreateDiscountCourseOrderResp, error) {
	d := models.DiscountCourse{}
	o := models.OrderCourse{}
	// todo 限制用户购买数量

	c := cron.New()
	spec := "*/15 * * * * ?"
	err := c.AddFunc(spec, func() {

	})
	fmt.Println(err)
	c.Start()

	const NUM = 2

	if in.Num > NUM {
		return nil, errors.New("课程一人限购两份")
	}

	courseId, err := d.GetDiscountCourseId(in.CourseId)
	if err != nil {
		return nil, errors.New("查询限时优惠课程失败")
	}
	num := courseId.Num - int(in.Num)
	if num < 0 {
		return nil, errors.New("库存不足")
	}

	//now := time.Now()
	//
	//StartTime, err := time.Parse(time.DateTime, courseId.StartTime)
	//if err != nil {
	//	return nil, err
	//}
	//EndTime, err := time.Parse(time.DateTime, courseId.EndTime)
	//if err != nil {
	//	return nil, err
	//}
	//if now.Before(StartTime) {
	//	return nil, errors.New("限制时间还未开启")
	//}
	//
	//if now.After(EndTime) {
	//	return nil, errors.New("限制时间已过")
	//}

	order, err := o.CreateDiscountCourseOrder(in, num, courseId.NowPrice)

	if err != nil {
		return nil, err
	}
	return &course.CreateDiscountCourseOrderResp{OrderId: int64(order.ID)}, nil
}
func OrderList(in *course.OrderListReq) (*course.OrderListResp, error) {
	u := models.User{}
	o := models.OrderCourse{}
	user, err := u.GetUserId(in.UserId)
	if err != nil {
		return nil, errors.New("用户查询失败")
	}
	if user.ID != 1 {
		return nil, errors.New("该用户不是管理员,无法列表统计")
	}
	orderlist, err := o.OrderList()
	if err != nil {
		return nil, errors.New("订单统计失败")
	}

	var list []*course.OrderList

	for _, i := range orderlist {
		Total := i.Price + i.Price
		list = append(list, &course.OrderList{
			OrderId:    int64(i.ID),
			UserId:     int64(i.UserId),
			CourseId:   int64(i.CourseId),
			OrderSn:    i.OrderSn,
			Num:        int64(i.Num),
			Price:      float32(i.Price),
			TotalPrice: float32(Total),
		})

	}
	return &course.OrderListResp{
		List: list,
	}, nil

}

func OrderPay(in *course.OrderPayReq) (*course.OrderPayResp, error) {
	c := models.Course{}
	u := models.User{}
	o := models.OrderCourse{}
	order, err := o.OrderId(in)
	if err != nil {
		return nil, err
	}
	fmt.Println(order.CourseId)
	var alipay string
	courses, err := c.GetCourseIds(int64(order.CourseId))
	if err != nil {
		return nil, err
	}
	fmt.Println(2222)
	user, err := u.GetUserId(int64(order.UserId))
	if err != nil {
		return nil, errors.New("用户查询失败")
	}
	float := strconv.FormatFloat(order.Price, 'E', -1, 64)
	fmt.Println(float)
	if in.Pay == 1 {

		alipay = pkg.Alipay(courses.Name, order.OrderSn, float)
	} else {
		num := user.Balance - order.Price
		if num < 0 {
			return nil, errors.New("用户余额不足")
		}
		initialize.DB.Model(&models.User{}).Where("id=?").Update("balance", num)
	}

	return &course.OrderPayResp{
		Success: true,
		Url:     alipay,
	}, nil

}
